<template>
  <div class="IndexNavbar">
    <!-- router 启用该模式会在激活导航时以 index 作为 path 进行路由跳转，无需通过代码进行跳转 -->
    <el-menu class="menu" :default-active="activeIndex" router mode="horizontal" background-color="white" text-color="#222" active-text-color="red">
      <el-menu-item v-for="(item, i) in navList" :key="i" :index="item.index">
        {{ item.navItemName }}
      </el-menu-item>
      <span class="project-title">WJBlogs</span>
      <span class="logout" v-if="online" @click="logout">登出</span>
      <span class="logout" v-else @click="toLoginPage">登录</span>
    </el-menu>
  </div>
</template>

<script>
export default {
  name: "IndexNavbar",
  data() {
    return {
      navList: [
        { index: "/index", navItemName: "首页" },
        { index: "/jotters", navItemName: "随笔" },
        { index: "/library", navItemName: "图书馆" },
        { index: "/admin", navItemName: "管理员" },
      ],
    };
  },
  computed: {
    // 当前激活的导航栏
    activeIndex() {
      // 判断当前路由是否是多级路径
      let childrenPath = this.$route.path.indexOf("/", 1);
      // 是多级路径
      if (childrenPath !== -1)
        return this.$route.path.substring(0, childrenPath);
      // 不是多级路径
      return this.$route.path;
    },
    online() {
      if (this.$store.state.user !== null) {
        return true;
      }
      return false;
    },
  },
  methods: {
    toLoginPage() {
      this.$router.push("/login");
    },
    async logout() {
      const { data: res } = await this.$http.get("/logout");
      if (res.code !== 200) return this.$message.error("登出失败");

      // 清空 vuex，并清空sessionStorage、localStorage、cookies
      this.$store.commit("logout");
      window.sessionStorage.clear();
      window.localStorage.clear();
      // clear cookies

      this.$message.success("登出成功");
      this.$router.push("/");
    },
  },
};
</script>

<style lang="less" scoped>
.IndexNavbar {
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.05);
}

.menu {
  min-width: 1300px;
  box-sizing: border-box;
}

.project-title {
  position: absolute;
  padding-top: 20px;
  right: 43%;
  font-size: 20px;
  font-weight: bold;
}

.logout {
  float: right;
  width: 48px;
  font-size: 16px;

  margin-top: 18px;
  margin-right: 39px;
  padding: 5px 5px 5px 5px;
  text-align: center;

  cursor: pointer;

  &:hover {
    color: red;
  }
}
</style>
